package com.ipzoe.common.captcha.repository;

import com.ipzoe.common.captcha.CaptchaCode;
import com.ipzoe.common.captcha.CaptchaCodeRepository;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认验证码存储器，存储在内存中
 * 
 * @author Eric
 * @date 2019/12/02
 */
@Slf4j
public class DefaultCaptchaCodeRepository implements CaptchaCodeRepository {

    private final static Map<String, CaptchaCode> MAP = new ConcurrentHashMap<>();

    @Override
    public CaptchaCode get(String key) {
        CaptchaCode code = MAP.get(key);
        log.debug("验证码存取的默认实现类 获取的键为 {},值为 ", key);
        return code;
    }

    @Override
    public void remove(String key) {
        Iterator<String> it = MAP.keySet().iterator();
        synchronized (DefaultCaptchaCodeRepository.class) {
            while (it.hasNext()) {
                String currentKey = it.next();
                MAP.keySet().remove(currentKey);
            }
        }
    }

    @Override
    public void save(String key, CaptchaCode code) {
        log.debug("验证码存取的默认实现类 保存的键为 {},值为 {}", key, code);
        MAP.put(key, code);
    }

}
